"use strict";

const { redis: RedisClient } = require("../connect");
const { FLayout, FEnum } = require("../util");
const config = require("../config/config");
const { driverProxy } = require("../proxy");

exports.getStrategyInfo = async ctx => {
  const strategy = await driverProxy.getStrategy();
  const { timeInterval, method: upgradeType } = strategy;
  FLayout.layout(null, ctx, {
    timeInterval,
    upgradeType
  });
};

exports.getLatestVerInfo = async ctx => {
  let resInfo = {};
  const loadQueue = FEnum.RedisKey.loadQueue;
  const slen = await RedisClient.scard(loadQueue);
  if (slen >= FEnum.MaxLimit.LimitLoad) {
    resInfo = {
      errNo: 3004,
      msg: "users overloaded",
      version: ctx.reqBody.curPackVer || "0.0.0.0"
    };
  } else {
    const info = await driverProxy.acquireLastVer(ctx.reqBody);
    if (!info)
      return FLayout.layout(null, ctx, { errNo: 3002, msg: "no driver found" });
    const { md5, fileSize, fileName, version } = info;
    resInfo = { md5, fileSize, fileName, version };
  }
  FLayout.layout(null, ctx, resInfo);
};

exports.getUpgradePack = async ctx => {
  const reqBody = ctx.reqBody;
  const info = await driverProxy.acquireDownload(reqBody);
  if (!info)
    return FLayout.layout(null, ctx, { errNo: 3002, msg: "no driver found" });
  const { httpPath: url } = info;
  FLayout.layout(null, ctx, { url });
};

exports.notifyDownRes = async ctx => {
  await driverProxy.saveDownRes(ctx.reqBody);
  FLayout.layout(null, ctx, { msg: "success" });
};

exports.upDevInstallRes = async ctx => {
  const file = ctx.request.files.file;
  await driverProxy.saveInstallRes(file, ctx.reqBody);
  FLayout.layout(null, ctx, { msg: "success" });
};

exports.getServerInfo = async ctx => {
  const { domain, port } = config;
  FLayout.layout(null, ctx, {
    method: "http",
    host: domain,
    port
  });
};
